/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package databaseserver;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 *
 * @author tinvukhac
 */
public class DatabaseImpl extends UnicastRemoteObject implements databaseinterface.DatabaseInterface {

    private DatabaseServerUI serverUI;

    public DatabaseImpl() throws RemoteException {
    }

    public DatabaseImpl(DatabaseServerUI serverUI) throws RemoteException {
        this.serverUI = serverUI;
    }

    // Implement the DatabaseInterface
    public String insertNewUser(String userId, String password, String ipAddress) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;"
                    + "databaseName=sharing;userName=sa;password=123456";
            Connection conn = DriverManager.getConnection(connectionUrl);
            Statement statement = conn.createStatement();
            String sqlQuery = "INSERT INTO users(userId, password, userAddress) VALUES('" + userId + "', '" + password + "', '" + ipAddress + "')";
            statement.executeUpdate(sqlQuery);
            conn.close();

            return "OK";
        } catch (Exception e) {
            return "SQL Exception : " + e.toString();
        }
    }

    public String checkLoginUser(String userId, String password, String ipAddress) {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            String connectionUrl = "jdbc:sqlserver://localhost:1433;"
                    + "databaseName=sharing;userName=sa;password=123456";
            Connection conn = DriverManager.getConnection(connectionUrl);
            Statement statement = conn.createStatement();
            String sqlQuery = "SELECT * FROM users WHERE userId = '" + userId + "' AND password = '" + password + "'";
            ResultSet rs = statement.executeQuery(sqlQuery);
            if (rs.next()) {
                // User is available, update ipAddress
                String updateQuery = "UPDATE users SET userAddress = '" + ipAddress + "' WHERE userId = '" + userId + "' ";
                statement.executeUpdate(updateQuery);
            } else {
                // User is unavailable
                conn.close();
                return "Username or password is incorrect";
            }
            conn.close();

            return "OK";
        } catch (Exception e) {
            return "SQL Exception : " + e.toString();
        }
    }
}
